<!DOCTYPE html>
<html>

<head>
	<meta charset="utf-8" />
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>手写Promise</title>
</head>

<body>
	<script>
		function myPromise(constructor) {
			let self = this;
			self.status = "pending";
			self.value = undefined;
			self.reason = undefined;

			function resolve(value) {
				if (self.status === "pending") {
					self.value = value;
					self.status = "resolved";
				}
			}

			function reject(reason) {
				if (self.status === "pending") {
					self.reason = reason;
					self.status = "rejected";
				}
			}

			try {
				constructor(resolve, reject);
			} catch (e) {
				reject(e)
			}
		}

		myPromise.prototype.then = function (onFullfilled, onRejected) {
			let self = this;
			switch (self.status) {
				case "resolved":
					onFullfilled(self.value);
					break;
				case "rejected":
					onRejected(self.reason);
					break;
				default: break;
			}
		}

		const promise1 = new Promise((resolve, reject) => {
			console.log('start');
			setTimeout(() => {
				resolve(1)
			}, 1000);
		})
		promise1.then((result) => {
			console.log(result);
		}, () => { })

		const promise2 = new myPromise((resolve, reject) => {
			resolve(2)
		})
		promise2.then((value) => {
			console.log(value);
		})
	</script>
</body>

</html>